package com.web.controller.lxf;

import com.core.dto.RoleDTO;
import com.core.dto.UserDTO;
import com.service.user.RoleService;
import com.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: lxf
 * Date: 2016/7/5
 * Time: 15:18
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/back/user")
public class UserManagerController {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    @RequestMapping(value = "form", method = RequestMethod.GET)
    public ModelAndView userFormInit(Model model) {
        List<RoleDTO> roleDTOs = roleService.findAllRole();
        model.addAttribute("roleDTOs", roleDTOs);
        model.addAttribute("roleMap", RoleDTO.toRoleMap(roleDTOs));
        return new ModelAndView("back/user/userUpdate", "userDTO", new UserDTO());
    }

    @RequestMapping(value = "form/{userGuid}", method = RequestMethod.GET)
    public ModelAndView userFormUpdateInit(@PathVariable String userGuid, Model model) {
        UserDTO userDTO = userService.findUserByGuid(userGuid);
        List<RoleDTO> roleDTOs = roleService.findAllRole();
        model.addAttribute("roleMap", RoleDTO.toRoleMap(roleDTOs));
        return new ModelAndView("back/user/userUpdate", "userDTO", userDTO);
    }

    @RequestMapping(value = "form", method = RequestMethod.POST)
    public String userForm(UserDTO userDTO) {
        userService.saveOrUpdateUser(userDTO);
        return "redirect:/back/user/list";
    }

    @RequestMapping(value = "list", method = RequestMethod.GET)
    public String userListIndex() {
        return "back/user/user";
    }

    @RequestMapping(value = "list/{currentPage}", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> userList(@PathVariable String currentPage) {
        return userService.findAllUser(currentPage);
    }

}
